package com.chief.hadoop.fs;


import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.junit.Test;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class HdfsAPI {

    String HDFS_PATH = "hdfs://hadoop52:8020/";

    @Test
    public void testStatus() throws IOException, URISyntaxException {
        Configuration conf = new Configuration();
        FileSystem fileSystem = FileSystem.get(new URI(HDFS_PATH), conf);
        FileStatus fileStatus = fileSystem.getFileStatus(new Path("/api/java.txt"));
        System.out.println(fileStatus.toString());
        System.out.println(fileStatus.getPath().getName());
        System.out.println(fileStatus.isFile());
    }

    @Test
    public void testRm() throws IOException, URISyntaxException {
        Configuration conf = new Configuration();
        FileSystem fileSystem = FileSystem.get(new URI(HDFS_PATH), conf);
        fileSystem.deleteOnExit(new Path("/api/java.txt"));
        fileSystem.deleteOnExit(new Path("/api"));
    }

    @Test
    public void testFile() throws IOException, URISyntaxException {
        Configuration conf = new Configuration();
        FileSystem fileSystem = FileSystem.get(new URI(HDFS_PATH), conf);
        fileSystem.mkdirs(new Path("/api"));
        fileSystem.createNewFile(new Path("/api/java.txt"));
        fileSystem.append(new Path("/api/java.txt")).writeBytes("\r\nappend it...");
    }


    @Test
    public void testMv() throws IOException, URISyntaxException {
        Configuration conf = new Configuration();
        FileSystem fileSystem = FileSystem.get(new URI(HDFS_PATH), conf);
        fileSystem.rename(new Path("/abcd/c.txt"), new Path("/cccc.txt"));
    }

    @Test
    public void testDownLoad() throws IOException, URISyntaxException {
        Configuration conf = new Configuration();
        FileSystem fileSystem = FileSystem.get(new URI(HDFS_PATH), conf);
        fileSystem.copyToLocalFile(false, new Path("/a.txt"), new Path("E:\\"), true);
    }

    @Test
    public void testLs() throws IOException, URISyntaxException {
        Configuration conf = new Configuration();
        FileSystem fileSystem = FileSystem.get(new URI(HDFS_PATH), conf);
        RemoteIterator<LocatedFileStatus> iterator = fileSystem.listFiles(new Path("/"), false);
        while (iterator.hasNext()) {
            System.out.println(iterator.next().getPath().getName());
        }
    }


    @Test
    public void testUpload() throws IOException, URISyntaxException {
        Configuration conf = new Configuration();
        FileSystem fileSystem = FileSystem.get(new URI(HDFS_PATH), conf);
        fileSystem.copyFromLocalFile(false, true, new Path("E:\\eclipse_code_format.xml"), new Path("/"));
    }


}
